package com.rem.lettuce.service;

import com.rem.lettuce.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Author Rem
 * @Date 2020-05-15
 * @Version 1.0
 */

@Service
@Slf4j
public class UserService {

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 获取数据
     *
     * @param key
     * @return
     */
    public String getString(String key) {
        log.info("RedisTemplate 打开");
        String msg;


        if (redisTemplate.hasKey(key)) {
            log.info("从redis中取出数据~");
            msg = (String) redisTemplate.opsForValue().get(key);
        } else {
            log.info("从数据库中取出数据~");
            msg = "redisTemplate测试";
            redisTemplate.opsForValue().set(key, msg);
        }
        return msg;
    }


    /**
     * 设置过期时间
     *
     * @param key
     * @return
     */
    public Boolean expireStr(String key) {
        log.info("设置过期时间~");
        return redisTemplate.expire(key, 3, TimeUnit.MINUTES);
    }


    /**
     * 从redis中取出数据
     * 1.先判断redis中有没有key
     * 2.有key值 直接从redis中取出数据
     * 3.没有key值，从数据库中查询数据，并且将数据存入redis中
     * 4.返回数据
     *
     * @param id
     * @return
     */
    public Object selectById(Long id) {
        User user = new User();
        if (redisTemplate.opsForHash().hasKey("user", id.toString())) {
            log.info("从redis中取出数据~~");
            return redisTemplate.opsForHash().get("user", id.toString());
        } else {
            user.setId(6L);
            user.setAge(13);
            user.setName("shimishi");
            redisTemplate.opsForHash().put("user", id.toString(), user.toString());
            log.info("从数据库中取出数据~~");
        }
        return user;
    }

}
